// 导入
import base_url from './config.js'

// 导出
// const = httpReq = (options) => { return new Promise((resolve,reject)=>{ ... }) }
function httpReq({
	url,
	token = '',
	data = {},
	method = "get"
}) {
	console.log(url, token, data, method);
	if (token) {
		token = "Bearer " + token;
	} else if (uni.getStorageSync('token')) {
		token = "Bearer " + uni.getStorageSync('token');
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + 'index.php/?r=' + url,
			method: method || 'get',
			data: data || {},
			header: {
				'Authorization': token || '',
				'Access-Control-Allow-Origin': '*',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				// console.log('授权：',!data.auth);
				// if (res.data.code == 401 && !data.auth) {
				// 	return uni.redirectTo({
				// 		url: '/pages/my/auth'
				// 	})
				// }
				// if (res.data.code != 200 && !data.auth) {
				// 	return uni.showToast({
				// 		title: res.data.msg,
				// 		icon: "error"
				// 	});
				// }
				resolve(res);
			},
			fail: (err) => {
				uni.showToast({
					title: "请求接口失败",
					icon: "error"
				});
				reject(err);
			}
		});
	})
}

function httpFile({
	url,
	filePath,
	token = '',
	data = {}
}) {
	if (token) {
		token = "Bearer " + token;
	} else if (uni.getStorageSync('token')) {
		token = "Bearer " + uni.getStorageSync('token');
	}
	if (!filePath) {
		uni.hideLoading();
		return uni.showToast({
			title: '上传内容不能为空',
			icon: 'error'
		})
	}
	console.log(url, filePath, token, data);
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: base_url + 'index.php/?r=' + url,
			filePath: filePath || {},
			name: 'file',
			fileType: 'image',
			header: {
				Authorization: token
			},
			// formData: {
			// 	// 'dirname': 'dir'
			// },
			formData: data,
			success: res => {
				// let json = JSON.parse(res);
				// console.log(res);
				// if (json.data.code == 401) {
				// 	return uni.redirectTo({
				// 		url: './pages/my/auth'
				// 	})
				// }
				
				resolve(res);
			},
			fail: err => {
				uni.showToast({
					title: "请求接口失败",
					icon: "error"
				});
				reject(err);
			}
		})
	});
}

export default {
	base_url,
	httpReq,
	httpFile
}
